﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebUI.Models;

namespace WebUI.Controllers
{
    [Authorize(Roles = "Admin,Engineer")]
    public class EngineerController : _SiteBaseController
    {
        //
        // GET: /Engineer/

        public ActionResult ResetPwd(string UserName, string AccessKey, string NewPassword)
        {
            string r = string.Empty;
            if (System.Configuration.ConfigurationManager.AppSettings["AllowResetEngineerPwd"] == "true"
                && System.Configuration.ConfigurationManager.AppSettings["ResetEngineerPwdAccessKey"] == AccessKey
                && !string.IsNullOrWhiteSpace(NewPassword)
                && NewPassword.Trim().Length >= 6
                && !string.IsNullOrWhiteSpace(UserName)
                )
            {

                var au = DB.aspnet_Users.Where(v => v.UserName == UserName).FirstOrDefault();
                if (null != au)
                {
                    if (au.aspnet_Roles.Where(v => v.RoleName == "Engineer" || v.RoleName == "Admin").Count() > 0)
                    {
                        var np = NewPassword.Trim();
                        var u = Membership.GetUser(UserName);
                        if (null != u)
                        {
                            u.ChangePassword(u.ResetPassword(), np);
                            return Content("Done!");
                        }
                        else
                        {
                            r += "user not in membership";
                        }
                    }
                    else
                    {
                        r += ("uesr must be a engineer.");
                    }
                }
                else
                {
                    r += ("user not exist.");
                }
            }



            r += "<ol><li>Set AppSettings.AllowResetEngineerPwd to 'true'.</li>";
            r += "<li>access this url with ?UserName=xxxxxxxx&NewPassword=xxxxxxx</li>";
            r += "<li>password length must >=6</li>";
            r += "<li>UserName can be:<ul>";
            foreach (var item in DB.aspnet_Roles.Where(v => v.RoleName == "Engineer").First().aspnet_Users)
            {
                r += "<li>" + item.UserName + "</li>";
            }
            r += "</ul></li>";
            return Content(r);
        }

        [ValidateInput(false)]
        public ActionResult SqlExec(string q, string submit)
        {
            //if (submit == "Exec")
            //{
            //    int i = DB.ExecuteStoreCommand(q);
            //    return Content(i.ToString());
            //}
            //else if (submit == "Query") { 
            //    DB.ExecuteStoreQuery<Models.Catalog>(
            //}
            return null;

        }

        [HttpGet]
        public ActionResult BucketUserImport()
        {
            return View();
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult BucketUserImport(string users)
        {
            string defaultpwd = "123456";
            string[] columns = null;
            int columncount = 0;
            bool isheader = true;
            List<string[]> rows = new List<string[]>();
            List<string> errorrows = new List<string>();

            int usernamecolidx = -1;
            int mobilecolidx = -1;

            List<aspnet_Users> usermodels = new List<aspnet_Users>();

            foreach (var line in users.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
            {
                if (isheader)
                {
                    isheader = false;
                    columns = line.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    columncount = columns.Length;
                    usernamecolidx = Array.IndexOf<string>(columns, "username");
                    mobilecolidx = Array.IndexOf<string>(columns, "mobilealias");
                    if (usernamecolidx == -1 || mobilecolidx == -1)
                    {
                        ModelState.AddModelError("format error", "必须有标头，且标头必须包含用户名列和手机号列。");
                        return View();
                    }

                    continue;
                }

                var fields = line.Split('\t');

                if (fields.Length != columncount)
                {
                    errorrows.Add("字段错误:" + line);
                    continue;
                }
                var username = fields[usernamecolidx];
                var mobile = fields[mobilecolidx];

                if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(mobile))
                {
                    errorrows.Add("必填错误:" + line);
                    continue;
                }

                usermodels.Add(RecuperFromRow(columns, fields));
            }

            if (errorrows.Count > 0)
            {
                ModelState.AddModelError("format error", "以下行格式和标头不匹配。\r\n" + string.Join("\r\n", errorrows.ToArray()));
                return View();
            }
            errorrows.Clear();
            foreach (aspnet_Users m in usermodels)
            {
                try
                {
                    RecuperCreate(m, defaultpwd);
                }
                catch (Exception ex)
                {
                    errorrows.Add("创建失败:" + m.UserName + ex.Message);
                }
            }
            if (errorrows.Count > 0)
            {
                ModelState.AddModelError("format error", "用户创建时失败。\r\n" + string.Join("\r\n", errorrows.ToArray()));
            }
            return View();
        }
        aspnet_Users RecuperFromRow(string[] cols, string[] fields)
        {
            aspnet_Users m = new aspnet_Users()
            {
                Address = GetFieldVal<string>("Address", cols, fields),
                BeiZhu = GetFieldVal<string>("BeiZhu", cols, fields),
                //BingQuID = GetFieldVal<string>("BingQuID", cols, fields),
                BirthDay = new DateTime(1990,1,1),//GetFieldVal<DateTime>("BirthDay", cols, fields),
                //DepartmentID = GetFieldVal<string>("DepartmentID", cols, fields),
                Email = "user@3ab.com.cn",
                Gender = GetFieldVal<string>("Gender", cols, fields),
                HomePhone = GetFieldVal<string>("HomePhone", cols, fields),
                HomePhoneB = GetFieldVal<string>("HomePhoneB", cols, fields),
                //HospitalID = GetFieldVal<string>("HospitalID", cols, fields),
                HuanZheLaiYuan = GetFieldVal<string>("HuanZheLaiYuan", cols, fields),
                IDCode = GetFieldVal<string>("IDCode", cols, fields),
                IDCodeType = GetFieldVal<string>("IDCodeType", cols, fields),
                MainRoleName = "Recuper",
                MobileAlias = GetFieldVal<string>("MobileAlias", cols, fields),
                MobileAliasB = GetFieldVal<string>("MobileAliasB", cols, fields),
                PostCode = GetFieldVal<string>("PostCode", cols, fields),
                SheBaoHao = GetFieldVal<string>("SheBaoHao", cols, fields),
                Title = GetFieldVal<string>("UserName", cols, fields),
                UserHeight = GetFieldVal<string>("UserHeight", cols, fields),
                UserId = Guid.Empty,
                UserName = GetFieldVal<string>("UserName", cols, fields),
                UserWeight = GetFieldVal<string>("UserWeight", cols, fields)
            };
            return m;
        }

        T GetFieldVal<T>(string name, string[] cols, string[] fields)
        {
            int i = Array.IndexOf<string>(cols, name.ToLower());
            if (i == -1) return default(T);
            try
            {
                T r = (T)Convert.ChangeType(fields[i], typeof(T));
                return r;
            }
            catch {
                return default(T);
            }
        }
        void RecuperCreate(aspnet_Users m, string Pwd)
        {
            aspnet_Users tm = null;
            if (m.UserId == Guid.Empty)
            {
                if (string.IsNullOrEmpty(m.UserName))
                {
                    throw new SiteException("请输入用户名！");
                }

                if (string.IsNullOrEmpty(m.MobileAlias))
                {
                    throw new SiteException("请输入手机号！");
                }
                if (string.IsNullOrEmpty(m.Gender))
                {
                    throw new SiteException("请选择患者性别！");
                }
                if (m.BirthDay == DateTime.MinValue)
                {
                    throw new SiteException("请输入出生日期！");
                }
                var lun = m.UserName.ToLower();
                if (DB.aspnet_Users.Any(v => v.LoweredUserName == lun||v.MobileAlias==m.MobileAlias))
                {
                    throw new SiteException("用户名或手机号已经在使用！");
                }

                if (string.IsNullOrWhiteSpace(Pwd))
                {
                    Pwd = m.MobileAlias;
                }
                try
                {
                    var mu = Membership.CreateUser(m.UserName, Pwd);
                    if (null == mu)
                    {
                        ModelState.AddModelError("", new Exception("Error when create user."));
                        throw new SiteException("创建用户遇到未知以外。");
                    }
                    System.Web.Security.Roles.AddUserToRole(mu.UserName, "Recuper");

                    tm = DB.aspnet_Users.Where(v => v.UserName == m.UserName).FirstOrDefault();
                    var uid = tm.UserId;
                    tm = DB.aspnet_Users.Where(v => v.UserId == uid).FirstOrDefault();

                    m.LoweredUserName = m.UserName.ToLower();
                    m.MainRoleName = "Recuper";
                    m.UserId = tm.UserId;
                    m.ApplicationId = tm.ApplicationId;
                    m.LastActivityDate = tm.LastActivityDate;
                    DB.aspnet_Users.ApplyCurrentValues(m);

                    DB.SaveChanges();

                }
                catch (Exception ex)
                {
                    try
                    {
                        Membership.DeleteUser(m.UserName, true);
                    }
                    catch { }
                    throw new SiteException(ex.Message);
                }
            }
        }

        [HttpGet]
        public ActionResult BucketEnHospitalDataImport()
        {
            return View();
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult BucketEnHospitalDataImport(string enhospdata)
        {
            string[] columns = null;
            int columncount = 0;
            bool isheader = true;
            List<string[]> rows = new List<string[]>();
            List<string> errorrows = new List<string>();

            int usernamecolidx = -1;
            int mobilecolidx = -1;

            List<Recuper> enhosps = new List<Recuper>();

            foreach (var line in enhospdata.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
            {
                if (isheader)
                {
                    isheader = false;
                    columns = line.Split(new char[] { '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    columncount = columns.Length;
                    usernamecolidx = Array.IndexOf<string>(columns, "username");
                    if (usernamecolidx == -1)
                    {
                        ModelState.AddModelError("format error", "必须有标头，且标头必须包含用户名列。");
                        return View();
                    }

                    continue;
                }

                var fields = line.Split('\t');

                if (fields.Length != columncount)
                {
                    errorrows.Add("字段错误:" + line);
                    continue;
                }
                var username = fields[usernamecolidx];

                if (string.IsNullOrEmpty(username))
                {
                    errorrows.Add("必填错误:" + line);
                    continue;
                }

                var user = DB.aspnet_Users.FirstOrDefault(v => v.UserName.ToLower() == username.ToLower());
                if (null == user)
                {
                    errorrows.Add("患者名错:" + line);
                    continue;
                }
                enhosps.Add(EnhospDataFromRow(user.UserId, columns, fields));
            }

            if (errorrows.Count > 0)
            {
                ModelState.AddModelError("format error", "以下行格式和标头不匹配。\r\n" + string.Join("\r\n", errorrows.ToArray()));
                return View();
            }
            errorrows.Clear();
            foreach (Recuper m in enhosps)
            {
                try
                {
                    DB.Recupers.AddObject(m);
                    DB.SaveChanges();
                }
                catch (Exception ex)
                {
                    errorrows.Add("创建失败:" + m.UserID + ex.Message);
                }
            }
            if (errorrows.Count > 0)
            {
                ModelState.AddModelError("format error", "用户创建时失败。\r\n" + string.Join("\r\n", errorrows.ToArray()));
            }
            return View();
        }
        Guid defaultdoctorid = Guid.Parse("7B158E28-86B0-4067-A60E-2E7C107300B5");
        private Recuper EnhospDataFromRow(Guid userid, string[] columns, string[] fields)
        {
            var r = new Recuper()
            {
                UserID = userid,
                RecuperID = DB.NewID()
                ,
                BingAnHao = GetFieldVal<int>("BingAnHao", columns, fields)
                ,
                HospitalID ="27780676"
                ,
                DepartmentID ="33314765"
                ,
                BingQuID = "27781061"
                ,
                EnHospDay = GetFieldVal<DateTime>("EnHospDay", columns, fields)
                ,
                DeHospDay = GetFieldVal<DateTime>("DeHospDay", columns, fields)
                ,
                DoctorID = defaultdoctorid
                ,
                ZhuYuanYiSheng = GetFieldVal<string>("ZhuYuanYiSheng", columns, fields)
                ,
                ZhenDuanS = GetFieldVal<string>("ZhenDuanS", columns, fields)
                ,
                ShouShuS = GetFieldVal<string>("ShouShuS", columns, fields)
                ,
                HuanZheLaiYuan = "导入"
                ,
                BeiZhu = GetFieldVal<string>("BeiZhu", columns, fields)
                ,
                SuiFangLeiXing = GetFieldVal<string>("SuiFangLeiXing", columns, fields)
                ,
                GuoQi = false
            };
            return r;
        }




    }
}
